export const createInputLimiter = (vm, options = {}) => {
    const { maxLines = 4, charsPerLine = 32, maxLength = 128, propName = 'displayText' } = options;

    // 计算字符串的字节长度（ASCII字符1字节，其他2字节）
    const getByteLength = (str) => {
        let length = 0;
        for (let i = 0; i < str.length; i++) {
            const charCode = str.charCodeAt(i);
            length += charCode <= 127 ? 1 : 2;
        }
        return length;
    };

    // 按字节长度截取字符串（避免截断双字节字符）
    const substringByByte = (str, maxBytes) => {
        let currentBytes = 0;
        let result = '';
        for (let i = 0; i < str.length; i++) {
            const charCode = str.charCodeAt(i);
            const charBytes = charCode <= 127 ? 1 : 2;

            if (currentBytes + charBytes > maxBytes) {
                break;
            }
            result += str[i];
            currentBytes += charBytes;
        }
        return result;
    };

    // 获取精确的行信息（基于字节长度）
    const getCurrentLineInfo = (value, cursorPos) => {
        const beforeCursor = value.substring(0, cursorPos);
        const lines = beforeCursor.split('\n');
        const currentLine = lines[lines.length - 1] || '';
        const currentLineByteLength = getByteLength(currentLine);
        return {
            lineIndex: lines.length - 1,
            lineText: currentLine,
            isLastLine: lines.length === maxLines,
            atLineEnd: currentLineByteLength >= charsPerLine
        };
    };

    const handleInput = (value) => {
        let newValue = value;
        let lines = newValue.split('\n');

        // 1. 处理非最后一行的溢出内容，按字节长度自动换行
        let processedLines = [];
        for (let i = 0; i < lines.length; i++) {
            let currentLine = lines[i];
            // 只处理非最后一行的溢出（如果还没到最大行数）
            while (processedLines.length < maxLines - 1 && getByteLength(currentLine) > charsPerLine) {
                // 按字节长度截取当前行最大允许长度
                const linePart = substringByByte(currentLine, charsPerLine);
                processedLines.push(linePart);
                // 剩余部分作为下一行
                currentLine = currentLine.substring(linePart.length);
            }
            processedLines.push(currentLine);
            // 超出最大行数则停止处理
            if (processedLines.length >= maxLines) break;
        }

        // 2. 限制总行数
        processedLines = processedLines.slice(0, maxLines);

        // 3. 最后一行严格按字节长度截断
        if (processedLines.length > 0) {
            const lastIdx = processedLines.length - 1;
            processedLines[lastIdx] = substringByByte(processedLines[lastIdx], charsPerLine);
        }

        // 4. 拼接处理后的内容
        newValue = processedLines.join('\n');

        // 5. 限制总字节长度
        if (getByteLength(newValue) > maxLength + maxLines * 2) {
            newValue = substringByByte(newValue, maxLength);
        }

        vm[propName] = newValue;
        return newValue;
    };

    const handleKeyDown = (e) => {
        if (e.ctrlKey || e.metaKey) return; // 允许快捷键

        const currentValue = vm[propName];
        const cursorPos = e.target.selectionStart;
        const { isLastLine, atLineEnd } = getCurrentLineInfo(currentValue, cursorPos);

        // 情况1：在最后一行阻止换行
        if (isLastLine && e.key === 'Enter') {
            e.preventDefault();
            return;
        }

        // 情况2：行满时阻止输入（允许编辑操作）
        if (atLineEnd && !['Backspace', 'Delete', 'ArrowLeft', 'ArrowRight', 'Tab'].includes(e.key)) {
            e.preventDefault();
            return;
        }

        // 情况3：全局字节长度限制
        if (getByteLength(currentValue) >= maxLength &&
            !['Backspace', 'Delete', 'ArrowLeft', 'ArrowRight'].includes(e.key)) {
            e.preventDefault();
        }
    };

    const handlePaste = (e) => {
        const currentValue = vm[propName];
        const textarea = e.target;
        const cursorPos = textarea.selectionStart;
        const { isLastLine, lineText } = getCurrentLineInfo(currentValue, cursorPos);

        let pasteText = e.clipboardData.getData('text/plain');
        const lineByteLength = getByteLength(lineText);
        const remainingLineBytes = isLastLine ? charsPerLine - lineByteLength : Infinity;
        const remainingTotalBytes = maxLength - getByteLength(currentValue);
        const maxPasteBytes = Math.min(remainingLineBytes, remainingTotalBytes);

        // 按允许的最大字节数截取粘贴内容
        const pasteContent = substringByByte(pasteText, maxPasteBytes);

        // 执行粘贴操作
        const start = textarea.selectionStart;
        const end = textarea.selectionEnd;
        const newValue = currentValue.substring(0, start) + pasteContent + currentValue.substring(end);

        // 通过handleInput处理粘贴后的内容
        vm[propName] = handleInput(newValue);

        // 设置光标位置
        vm.$nextTick(() => {
            textarea.setSelectionRange(start + pasteContent.length, start + pasteContent.length);
        });
    };

    return { handleInput, handleKeyDown, handlePaste };
};
